package com.lzq.course.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzq.course.server.domain.${Domain};
import com.lzq.course.server.domain.${Domain}Example;
import com.lzq.course.server.dto.${Domain}Dto;
import com.lzq.course.server.dto.PageDto;
import com.lzq.course.server.mapper.${Domain}Mapper;
import com.lzq.course.server.util.CopyUtil;
import com.lzq.course.server.util.UuidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
<#list typeSet as type>
    <#if type=='Date'>
import java.util.Date;
    </#if>
</#list>

@Service
public class ${Domain}Service {

    @Resource
    private ${Domain}Mapper ${domain}Mapper;

    /**
     * example 这个文件很有用
     * 可以帮我们生成where order 查询
     * 不用单独写sql的增删改查
     */
    public void list(PageDto<${Domain}Dto> pageDto) {
        // 分页查询 页码不是从0开始
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());

        // 排序
        ${Domain}Example ${domain}Example = new ${Domain}Example();
        <#list fieldList as field>
            <#if field.nameHump=='sort'>
        ${domain}Example.setOrderByClause("sort asc");
            </#if>
        </#list>

        // 查询
        List<${Domain}> ${domain}List = ${domain}Mapper.selectByExample(${domain}Example);

        PageInfo<${Domain}> pageInfo = new PageInfo<>(${domain}List);
        pageDto.setTotal(pageInfo.getTotal());

        List<${Domain}Dto> ${domain}DtoList = CopyUtil.copyList(${domain}List, ${Domain}Dto.class);

        pageDto.setList(${domain}DtoList);
    }

    /**
     * 保存 修改
     * @param ${domain}Dto
     */
    public void save(${Domain}Dto ${domain}Dto) {
        //BeanUtils.copyProperties(${domain}Dto, ${domain});
        ${Domain} copy${Domain} = CopyUtil.copy(${domain}Dto, ${Domain}.class);

        if (StringUtils.isEmpty(${domain}Dto.getId())) {
            // 新增
            // 八位的 id
            copy${Domain}.setId(UuidUtil.getShortUuid());

            Date now = new Date();
        <#list fieldList as field>
            <#if field.nameHump=='createAt'>
            ${domain}.setCreateAt(now);
            </#if>
            <#if field.nameHump=='updateAt'>
            ${domain}.setUpdateAt(now);
            </#if>
        </#list>

            ${domain}Mapper.insert(copy${Domain});
        } else {
            // 编辑
        <#list fieldList as field>
            <#if field.nameHump=='updateAt'>
            ${domain}.setUpdateAt(now);
            </#if>
        </#list>
            ${domain}Mapper.updateByPrimaryKey(copy${Domain});
        }
    }

    /**
     * 删除
     * @param id
     */
    public void delete(String id) {
        ${domain}Mapper.deleteByPrimaryKey(id);
    }
}
